﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.DBModule;
using ZX.BLL;
using ZX.EHR.Library;
using ZX.DAL.DBExtend;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using ZX.BLL.Extend;
using ZX.Common;

//==================================================================
// Copyright (C) 2011 深圳市中旭企业管理股份有限公司
// 作 者：
// Email: 
// 日 期：
// 描 述：
// 版 本：1.0.0.0    
//    
//==================================================================

namespace ZX.EHR.Web
{
    public partial class workTimeAjax : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string flag = this.GetStringFromQueryString("flag", "");
            switch (flag.ToLower())
            {
                case "vacationcode":
                    GetSequenceCode("Vacation");
                    break;
                case "billid":
                    GetBillTypeID(this.GetStringFromQueryString("billtype", ""));
                    break;
                case "saveworktime":
                    SaveWorktime();
                    break;
                case "savewkdeptcalendersolution"://保存部门日历信息
                    SaveDeptCalender();
                    break;
                case "deleteworktime":
                    DeleteWorkTime();
                    break;
                case "deletevation":
                    DeleteVation();
                    break;
                case "savenocarddata":
                    SaveNoCardDataConfige();
                    break;
                case "savenoworkresult":  //saveNoWorkResult
                    saveNoWorkResultConfig();
                    break;
                case "savescheduling":
                    SaveScheduling();
                    break;
                case "deletewkcalendersolution":
                    deletewkCalender();
                    break;
                case "getworktimeselect":
                    CreateWorkTimeSelect();
                    break;
                case "updateconfirmworkresult":
                    Updateconfirmworkresult();
                    break;
                case "importbpmqianka":
                    ImportBPMQianKa();
                    break;
                case "importworkbillfrombpm_overtime":
                    ImportWorkBillFromBPM_OVERTIME();
                    break;
                case "importworkbillfrombpm_leave":
                    ImportWorkBillFromBPM_LEAVE();
                    break;
                case "importworkbillfrombpm_overtimeleave":
                    ImportWorkBillFromBPM_OVERTIMELEAVE();
                    break;
                case "importworkbillfrombpm_trip":
                    ImportWorkBillFromBPM_TRIP();
                    break;
                case "calcremovertimeleave":
                    CalcRemOvertimeLeave();
                    break;
                case "statworkresult":
                    StatWorkResult();
                    break;
                case "confirmworkresult_calc":
                    ConfirmWorkResult_Calc();
                    break;
                case "getworkflowinfo":
                    GetWorkFlowInfo();
                    break;
                case "getworkresult":
                    GetWorkResult();
                    break;
                case "getchildcategorynextseq":
                    GetChildCategoryNextSeq();
                    break;
                case "isdelcoreempclass":
                    IsDelCoreEmpClass();
                    break;
                case "isexistscoreempclass":
                    IsExistsCoreEmpClass();
                    break;
                case "savedatdutyinfo":
                    SaveDatDutyInfo();
                    break;
                case "deldatdutyinfo":
                    DelDatDutyInfo();
                    break;

                default:
                    break;
            }
        }

        #region 考勤单据
        /// <summary>
        /// 通过单据名字获取单据类型ID
        /// </summary>
        /// <param name="billtype"></param>
        public void GetBillTypeID(string billtype)
        {
            try
            {
                ZX.SYS.Library.DatPhraseDetail instance = ZX.Common.Globals.getEntity("DatPhraseDetail") as ZX.SYS.Library.DatPhraseDetail;
                ZX.BLL.Extend.BaseBussnies datBll = new ZX.BLL.Extend.BaseBussnies(instance);
                string condition = string.Format("PhraseValue='{0}'", billtype);
                ZX.SYS.Library.DatPhraseDetail datPhraseDetail = datBll.GetEntityByCondition(condition) as ZX.SYS.Library.DatPhraseDetail;
                string prefix = "";
                switch (billtype)
                {
                    case "TRIP":
                        prefix = "CC";
                        break;
                    case "OVERTIMELEAVE":
                        prefix = "TX";
                        break;
                    case "OVERTIME":
                        prefix = "JB";
                        break;
                    case "LEAVE":
                        prefix = "XJ";
                        break;
                    default:
                        break;
                }
                string billCode = GetBillCode(datPhraseDetail.PhraseID.ToString(), prefix);
                HttpContext.Current.Response.Write(datPhraseDetail.PhraseID + "|" + billCode);
                return;
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 生成单据编号
        /// </summary>
        /// <param name="billId">单据类型ID</param>
        /// <param name="prefix">单据编号前缀</param>
        public string GetBillCode(string billId, string prefix)
        {
            try
            {
                Int64 billCode = 10000;
                Int64 defaultCode = 10000;
                string billDate = DateTime.Now.ToString("yyyyMMdd");
                //获取编号
                string sql = string.Format(@"select IsNull(Max(BillCode),0) as BillCode from wkWorkBill  where  BillTypeID ='{0}'", billId);
                ZX.EHR.Library.wkWorkBill instance = ZX.Common.Globals.getEntity("wkWorkBill") as ZX.EHR.Library.wkWorkBill;
                ZX.BLL.Extend.BaseBussnies WorkBillBll = new ZX.BLL.Extend.BaseBussnies(instance);
                ZX.EHR.Library.wkWorkBill workBill = WorkBillBll.GetEntityBySqlComm(sql) as ZX.EHR.Library.wkWorkBill;
                string maxCode = workBill.BillCode;
                if (maxCode.Length > 10)
                {
                    Int64.TryParse(maxCode.Substring(10), out billCode);
                    billDate = maxCode.Substring(2, 8);
                }
                else
                {
                    billCode = 0;
                }
                billCode = billCode == 0 ? defaultCode : billCode;
                if (billDate == DateTime.Now.ToString("yyyyMMdd"))
                {
                    billCode++;
                    billCode = Convert.ToInt64(billDate + billCode.ToString());
                }
                else
                {
                    billCode = 10001;
                    billCode = Convert.ToInt64(DateTime.Now.ToString("yyyyMMdd") + billCode.ToString());
                }
                return prefix + billCode.ToString();
            }
            catch
            {
                return "-1";
            }
        }

        /// <summary>
        /// 生成流水单号
        /// </summary>
        /// <param name="sequenceName">序列名</param>
        /// <returns></returns>
        public void GetSequenceCode(string sequenceName)
        {
            //实例化序列实体
            BaseEntity instance = ZX.Common.Globals.getEntity("Sequence") as BaseEntity;
            ZX.BLL.Extend.BaseBussnies SequenceBll = new ZX.BLL.Extend.BaseBussnies(instance);
            //生成具体序列对象
            Sequence sequence = SequenceBll.GetEntityByCondition<Sequence>(string.Format("SequenceName='{0}'", sequenceName));
            //生成当前流水号
            Int64 curNum = IDMaker.GetSequenceNum(sequenceName);
            //组装当前编号
            HttpContext.Current.Response.Write(sequence.Preposition + curNum.ToString());
        }
        #endregion

        #region 班次
        /// <summary>
        /// 保存班次适用的部门或岗位信息
        /// </summary>
        /// <returns></returns>
        public void SaveWorktime()
        {
            string ids = this.GetStringFromQueryString("ids", "");
            string nams = this.GetStringFromQueryString("nams", "");
            string entity = this.GetStringFromQueryString("entity", "");
            string workTimeId = this.GetStringFromQueryString("workTimeId", "");
            switch (entity.ToLower())
            {
                case "wkdeptworktime":
                    SaveWorktimeForDept(ids, nams, workTimeId);
                    break;
                case "wkpositionworktime":
                    SaveWorktimeForPost(ids, nams, workTimeId);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 保存部门班次
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="nams"></param>
        /// <param name="workTimeId"></param>
        /// <returns></returns>
        public void SaveWorktimeForDept(string ids, string nams, string workTimeId)
        {
            try
            {
                ZX.EHR.Library.wkDeptWorkTime instance = ZX.Common.Globals.getEntity("wkDeptWorkTime") as ZX.EHR.Library.wkDeptWorkTime;
                ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(instance);
                //先删除
                bll.delete(string.Format("WorkTimeID='{0}'", workTimeId));
                //新增
                foreach (string id in ids.Split(','))
                {
                    instance.DeptID = Guid.Parse(id);
                    instance.WorkTimeID = Guid.Parse(workTimeId);
                    bll.Insert();
                }
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 保存岗位班次
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="nams"></param>
        /// <param name="workTimeId"></param>
        /// <returns></returns>
        public void SaveWorktimeForPost(string ids, string nams, string workTimeId)
        {
            try
            {
                ZX.EHR.Library.wkPositionWorkTime instance = ZX.Common.Globals.getEntity("wkPositionWorkTime") as ZX.EHR.Library.wkPositionWorkTime;
                ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(instance);
                //先删除
                bll.delete(string.Format("WorkTimeID='{0}'", workTimeId));
                //新增
                foreach (string id in ids.Split(','))
                {
                    instance.PostitionID = Guid.Parse(id);
                    instance.WorkTimeID = Guid.Parse(workTimeId);
                    bll.Insert();
                }
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 班次删除
        /// </summary>
        public void DeleteWorkTime()
        {
            try
            {
                //string workTimeID = this.GetStringFromQueryString("id", "");
                string workTimeID = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");

                if (workTimeID == string.Empty)
                {
                    HttpContext.Current.Response.Write("-1"); //班次ID为空
                    return;
                }
                workTimeID = "'" + workTimeID.Replace(",", "','") + "'";
                BaseEntity instance = null;
                ZX.BLL.Extend.BaseBussnies baseBll = null;
                string condition = "";
                bool isDelete = true;
                //定义引用表
                string[] tableName = { "wkDeptWorkTime", "wkPositionWorkTime", "wkScheduling", "wkWorkResult" };
                //先查询是否被引用了，如果有引用则不能删除，给提示
                foreach (string s in tableName)
                {
                    instance = ZX.Common.Globals.getEntity(s) as BaseEntity;
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    condition = string.Format("WorkTimeID in ({0})", workTimeID);
                    isDelete = (baseBll.GetEntityByCondition(condition) == null);
                    if (!isDelete) break;
                }
                if (isDelete)
                {
                    //删除各引用表数据
                    foreach (string s in tableName)
                    {
                        instance = ZX.Common.Globals.getEntity(s) as BaseEntity;
                        condition = string.Format("WorkTimeID  in ({0})", workTimeID);
                        baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                        baseBll.delete(condition);
                    }
                    //删除班次子表
                    instance = ZX.Common.Globals.getEntity("wkWorkTimeDetail") as BaseEntity;
                    condition = string.Format("WorkTimeID  in ({0})", workTimeID);
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    baseBll.delete(condition);
                    //删除主表
                    instance = ZX.Common.Globals.getEntity("wkWorkTime") as BaseEntity;
                    condition = string.Format("ID  in ({0})", workTimeID);
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    baseBll.delete(condition);
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");  //有引用则不能删除
                    return;
                }
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write("e" + e.Message);
            }
        }

        #endregion

        #region 日历
        /// <summary>
        /// 保存部门日历
        /// </summary>
        public void SaveDeptCalender()
        {
            try
            {
                string ids = this.GetStringFromQueryString("ids", "");
                string CalenderSolutionID = this.GetStringFromQueryString("CalenderSolutionID", "");
                if (ids != string.Empty && CalenderSolutionID != string.Empty)
                {
                    wkDeptCalenderSolution instance = new wkDeptCalenderSolution();
                    ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(instance);
                    foreach (string deptId in ids.Split(','))
                    {
                        object o = bll.GetEntityByCondition(string.Format("DeptID='{0}' and CalenderSolutionID='{1}'", deptId, CalenderSolutionID));
                        wkDeptCalenderSolution tempDeptCalendar = o == null ? null : o as wkDeptCalenderSolution;
                        if (o == null) //不存在，则新增
                        {
                            tempDeptCalendar = new wkDeptCalenderSolution();
                            tempDeptCalendar.ID = Guid.NewGuid();
                            tempDeptCalendar.CalenderSolutionID = new Guid(CalenderSolutionID);
                            tempDeptCalendar.DeptID = new Guid(deptId);
                            tempDeptCalendar.AddUser = this.User.UserID;
                            tempDeptCalendar.AddTime = DateTime.Now;
                            bll.Insert(tempDeptCalendar);
                        }
                        else //存在，修改
                        {
                            tempDeptCalendar.CalenderSolutionID = new Guid(CalenderSolutionID);
                            bll.Update(tempDeptCalendar);
                        }
                    }
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("-1");
                }
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write("e" + e.Message);
            }
        }
        /// <summary>
        /// 删除日历数据
        /// </summary>
        public void deletewkCalender()
        {
            string CalenderSolutionID = this.GetStringFromQueryString("id", "");
            if (CalenderSolutionID == string.Empty)
            {
                HttpContext.Current.Response.Write("eid为空！");
                return;
            }
            try
            {
                wkCalendar wkcalendar = new wkCalendar();
                ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(wkcalendar);
                bll.delete("SolutionID='" + CalenderSolutionID + "'");
                HttpContext.Current.Response.Write("0");
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write("e" + e.Message);
            }
        }
        #endregion

        #region 假期类型
        /// <summary>
        /// 假期类型删除
        /// </summary>
        public void DeleteVation()
        {
            try
            {
                string id = this.GetStringFromQueryString("id", "");
                if (id == string.Empty)
                {
                    HttpContext.Current.Response.Write("-1"); //ID为空
                    return;
                }
                BaseEntity instance = null;
                ZX.BLL.Extend.BaseBussnies baseBll = null;
                string condition = "";
                bool isDelete = true;
                //先查询是否被引用了，如果有引用则不能删除，给提示
                instance = ZX.Common.Globals.getEntity("wkWorkBill") as BaseEntity;
                baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                condition = string.Format(@"BillTypeID in 
                        (
	                        select  PhraseID
	                        from DatPhraseDetail 
	                        where ClassID = (select ClassID from DatPhraseClass where ClassValue='BillType')
	                        and PhraseValue in('LEAVE','OVERTIMELEAVE')
                        )
                        and VacationID='{0}'", id);
                isDelete = (baseBll.GetEntityByCondition(condition) == null);
                if (isDelete)
                {
                    //删除
                    instance = ZX.Common.Globals.getEntity("wkVacation") as BaseEntity;
                    condition = string.Format("ID='{0}'", id);
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    baseBll.delete(condition);
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");  //有引用则不能删除
                    return;
                }
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write("e" + e.Message);
            }
        }

        #endregion

        #region 无需打卡配置
        /// <summary>
        /// 保存无需打卡配置
        /// </summary>
        /// <returns></returns>
        public void SaveNoCardDataConfige()
        {
            string ids = this.GetStringFromQueryString("ids", "");
            string nams = this.GetStringFromQueryString("nams", "");
            string entity = this.GetStringFromQueryString("entity", "");
            string configTypeID = "DeptID";
            try
            {
                ZX.EHR.Library.wkNoCardDataConfig instance = ZX.Common.Globals.getEntity("wkNoCardDataConfig") as ZX.EHR.Library.wkNoCardDataConfig;
                ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(instance);
                //新增
                foreach (string id in ids.Split(','))
                {
                    instance.ConfigType = entity;
                    switch (entity.ToUpper())
                    {
                        case "DEPT":
                            instance.DeptID = Guid.Parse(id);
                            configTypeID = "DeptID";
                            break;
                        case "POSITION":
                            instance.PositionID = Guid.Parse(id);
                            configTypeID = "PositionID";
                            break;
                        case "PERSON":
                            instance.EmployeeID = Guid.Parse(id);
                            configTypeID = "EmployeeID";
                            break;
                        default:
                            break;
                    }
                    //先删除
                    bll.delete(string.Format("ConfigType='{0}' and {1}='{2}'", entity, configTypeID, id));
                    bll.Insert();
                }
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }

        }

        #endregion

        #region 不记考勤配置
        /// <summary>
        /// 不记考勤配置
        /// </summary>
        /// <returns></returns>
        public void saveNoWorkResultConfig()
        {
            string ids = this.GetStringFromQueryString("ids", "");
            string nams = this.GetStringFromQueryString("nams", "");
            string entity = this.GetStringFromQueryString("entity", "");
            string configTypeID = "DeptID";
            string ConfigType = "";
            Guid DeptID = Guid.Empty, PositionID = Guid.Empty, EmployeeID = Guid.Empty;
            try
            {
                DbSql dbsql = new DbSql();  
                //新增
                foreach (string id in ids.Split(','))
                {
                    ConfigType = entity;
                    DeptID = Guid.Empty;
                    PositionID = Guid.Empty;
                    EmployeeID = Guid.Empty;
                    switch (entity.ToUpper())
                    {
                        case "DEPT":
                            DeptID = Guid.Parse(id);
                            configTypeID = "DeptID";
                            break;
                        case "POSITION":
                            PositionID = Guid.Parse(id);
                            configTypeID = "PositionID";
                            break;
                        case "PERSON":
                            EmployeeID = Guid.Parse(id);
                            configTypeID = "EmployeeID";
                            break;
                        default:
                            break;
                    }
                    //先删除
                    dbsql.ExecuteSql(string.Format("Delete from wkNoWorkResultConfig where ConfigType='{0}' and {1}='{2}'", ConfigType, configTypeID, id));
                    //写入
                    dbsql.ExecuteSql(string.Format("Insert into wkNoWorkResultConfig(ID,ConfigType,DeptID,PositionID,EmployeeID) Values(newid(),'{0}','{1}','{2}','{3}')", ConfigType, DeptID,PositionID,EmployeeID));
                    
                    //bll.delete(string.Format("ConfigType='{0}' and {1}='{2}'", entity, configTypeID, id));
                    //bll.Insert();
                }
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }

        }

        #endregion

        #region 员工排班
        /// <summary>
        /// 员工排班
        /// </summary>
        private void SaveScheduling()
        {
            try
            {
                string ids = this.GetStringFromQueryString("ids", "");
                string beginDate = this.GetStringFromQueryString("beginDate", "");
                string endDate = this.GetStringFromQueryString("endDate", "");
                string workTimeID = this.GetStringFromQueryString("workTimeID", "");

                DbSql dbsql = new DbSql();
                IDataParameter[] parameters = new SqlParameter[6];
                parameters[0] = new SqlParameter("@beginDate", SqlDbType.Date);
                parameters[0].Value = beginDate;
                parameters[1] = new SqlParameter("@endDate", SqlDbType.Date);
                parameters[1].Value = endDate;
                parameters[2] = new SqlParameter("@workTimeID", SqlDbType.VarChar, 100);
                parameters[2].Value = workTimeID;
                parameters[3] = new SqlParameter("@empID", SqlDbType.VarChar, 4000);
                parameters[3].Value = ids;
                parameters[4] = new SqlParameter("@AddUser", SqlDbType.VarChar, 100);
                parameters[4].Value = this.UserId.ToString();
                parameters[5] = new SqlParameter("@EditWho", SqlDbType.VarChar, 100);
                parameters[5].Value = this.UserId.ToString();
                dbsql.RunProcedureNoQuery("sp_HR_EmpScheduling", parameters, true);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }
        #endregion

        #region 单个员工考勤统计
        /// <summary>
        /// 读取签卡数据
        /// </summary>
        private void ImportBPMQianKa()
        {
            try
            {
                IDataParameter[] parameters = new SqlParameter[4];
                ImportWorkBillFromBPM_PARA(parameters);
                string msg = ImportWorkBillFromBPM_EXEC("sp_HR_ImportBPMQianKa", parameters, true);
                HttpContext.Current.Response.Write("1" + msg);
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 读取加班流程
        /// </summary>
        private void ImportWorkBillFromBPM_OVERTIME()
        {
            try
            {
                IDataParameter[] parameters = new SqlParameter[4];
                ImportWorkBillFromBPM_PARA(parameters);
                string msg = ImportWorkBillFromBPM_EXEC("sp_HR_ImportWorkBillFromBPM_OVERTIME", parameters, true);
                HttpContext.Current.Response.Write("1" + msg);
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 读取请假流程
        /// </summary>
        private void ImportWorkBillFromBPM_LEAVE()
        {
            try
            {
                IDataParameter[] parameters = new SqlParameter[4];
                ImportWorkBillFromBPM_PARA(parameters);
                string msg = ImportWorkBillFromBPM_EXEC("sp_HR_ImportWorkBillFromBPM_LEAVE", parameters, true);
                HttpContext.Current.Response.Write("1" + msg);
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 读取调休流程
        /// </summary>
        private void ImportWorkBillFromBPM_OVERTIMELEAVE()
        {
            try
            {
                IDataParameter[] parameters = new SqlParameter[4];
                ImportWorkBillFromBPM_PARA(parameters);
                string msg = ImportWorkBillFromBPM_EXEC("sp_HR_ImportWorkBillFromBPM_OVERTIMELEAVE", parameters, true);
                HttpContext.Current.Response.Write("1" + msg);
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 读取出差流程
        /// </summary>
        private void ImportWorkBillFromBPM_TRIP()
        {
            try
            {
                IDataParameter[] parameters = new SqlParameter[4];
                ImportWorkBillFromBPM_PARA(parameters);
                string msg = ImportWorkBillFromBPM_EXEC("sp_HR_ImportWorkBillFromBPM_TRIP", parameters, true);
                HttpContext.Current.Response.Write("1" + msg);
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 累计加班、剩余调休时长
        /// </summary>
        private void CalcRemOvertimeLeave()
        {
            try
            {
                IDataParameter[] parameters = new SqlParameter[4];
                ImportWorkBillFromBPM_PARA(parameters);
                string msg = ImportWorkBillFromBPM_EXEC("sp_HR_CalcRemOvertimeLeave", parameters, true);
                HttpContext.Current.Response.Write("1" + msg);
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 导入BPM流程_参数准备
        /// </summary>
        private void ImportWorkBillFromBPM_PARA(IDataParameter[] parameters)
        {
            string statType = this.GetStringFromQueryString("statType", "");
            string beginDate = this.GetStringFromQueryString("beginDate", "");
            string endDate = this.GetStringFromQueryString("endDate", "");
            string deptIds = this.GetStringFromQueryString("deptIds", "");
            string empID = this.GetStringFromQueryString("emp", "");

            parameters[0] = new SqlParameter("@beginDate", SqlDbType.Date);
            parameters[0].Value = beginDate;
            parameters[1] = new SqlParameter("@endDate", SqlDbType.Date);
            parameters[1].Value = endDate;
            parameters[2] = new SqlParameter("@EmployeeID1", SqlDbType.VarChar, 100);
            parameters[2].Value = empID;
            parameters[3] = new SqlParameter("@Message", SqlDbType.VarChar, 4000);
            parameters[3].Direction = ParameterDirection.Output;
        }

        /// <summary>
        /// 导入BPM流程_执行存储过程
        /// </summary>
        /// <param name="ProcedureName">要调用的存储过程名</param>
        /// <param name="parameters">参数集合</param>
        /// <param name="bl"></param>
        /// <returns></returns>
        private string ImportWorkBillFromBPM_EXEC(string ProcedureName, IDataParameter[] parameters, bool bl)
        {
            DbSql dbsql = new DbSql();
            dbsql.RunProcedureNoQuery(ProcedureName, parameters, true);
            return parameters[3].Value.ToString();
        }

        /// <summary>
        /// 考勤明细计算
        /// </summary>
        private void StatWorkResult()
        {
            try
            {
                string statType = this.GetStringFromQueryString("statType", "");
                string beginDate = this.GetStringFromQueryString("beginDate", "");
                string endDate = this.GetStringFromQueryString("endDate", "");
                string deptIds = this.GetStringFromQueryString("deptIds", "");
                string empID = this.GetStringFromQueryString("emp", "");

                IDataParameter[] parameters = new SqlParameter[3];
                parameters[0] = new SqlParameter("@beginDate", SqlDbType.Date);
                parameters[0].Value = beginDate;
                parameters[1] = new SqlParameter("@endDate", SqlDbType.Date);
                parameters[1].Value = endDate;
                parameters[2] = new SqlParameter("@EmployeeID1", SqlDbType.VarChar, 100);
                parameters[2].Value = empID;
                DbSql dbsql = new DbSql();
                dbsql.RunProcedureNoQuery("sp_HR_StatWorkResult", parameters, true);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        /// <summary>
        /// 考勤确认表更新
        /// </summary>
        private void ConfirmWorkResult_Calc()
        {
            try
            {
                string statType = this.GetStringFromQueryString("statType", "");
                string beginDate = this.GetStringFromQueryString("beginDate", "");
                string endDate = this.GetStringFromQueryString("endDate", "");
                string deptIds = this.GetStringFromQueryString("deptIds", "");
                string empID = this.GetStringFromQueryString("emp", "");
                string yearMonth = beginDate.Substring(0, 7);

                IDataParameter[] parameters = new SqlParameter[2];
                parameters[0] = new SqlParameter("@YearMonth", SqlDbType.VarChar,7);
                parameters[0].Value = yearMonth;
                parameters[1] = new SqlParameter("@EmployeeID1", SqlDbType.VarChar, 100);
                parameters[1].Value = empID;
                DbSql dbsql = new DbSql();
                dbsql.RunProcedureNoQuery("sp_HR_ConfirmWorkResult_Calc", parameters, true);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }



        #endregion

        #region 更新考勤确认表中的符号
        /// <summary>
        /// 更新考勤确认表中的符号
        /// </summary>
        private void Updateconfirmworkresult()
        {
            try
            {
                string strJson = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");
                string employeeID = strJson.Split(',')[0];
                string workDate = strJson.Split(',')[1];
                string status = strJson.Split(',')[2];

                DbSql dbsql = new DbSql();

                string sql = string.Format("select WkStatus from wkWorkResult where EmployeeID='{0}' and WorkDate ='{1}' ", employeeID, workDate);

                status = dbsql.ExecuteQuery(sql).Rows[0]["WkStatus"].ToString();

                IDataParameter[] parameters = new SqlParameter[3];
                parameters[0] = new SqlParameter("@EmployeeID", SqlDbType.VarChar, 100);
                parameters[0].Value = employeeID;
                parameters[1] = new SqlParameter("@WorkDate", SqlDbType.Date);
                parameters[1].Value = workDate;
                parameters[2] = new SqlParameter("@Status", SqlDbType.VarChar, 100);
                parameters[2].Value = status;
                dbsql.RunProcedureNoQuery("sp_HR_ConfirmWorkResult", parameters, true);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }
        #endregion

        #region 创建班次下拉框
        /// <summary>
        /// 创建班次下拉框
        /// </summary>
        private void CreateWorkTimeSelect()
        {
            DbSql dbsql = new DbSql();
            string sql = "select Name as DisplayMember,id as ValueMember from wkWorkTime order by Name";
            DataTable dt = dbsql.ExecuteQuery(sql);
            StringBuilder strHtml = new StringBuilder("");
            string option = "<option value=\"{0}\">{1}</option>";
            foreach (DataRow dr in dt.Rows)
            {
                strHtml.Append(string.Format(option, dr["ValueMember"].ToString(), dr["DisplayMember"].ToString()));
            }
            HttpContext.Current.Response.Write(strHtml.ToString());
        }
        #endregion

        #region 获取流程信息
        /// <summary>
        /// 获取流程信息
        /// </summary>
        public void GetWorkFlowInfo()
        {
            try
            {
                string workFlowNo = this.GetStringFromQueryString("workFlowNo", "");
                if (workFlowNo == string.Empty)
                {
                    HttpContext.Current.Response.Write("-1"); //ID为空
                    return;
                }
                DbSql dbSql = new DbSql();
                string sql = "select top 1 * from  HF_WorkFlowInstanceView where WorkFlowNo='{0}' order by OperDateTime desc";
                DataTable dt = dbSql.ExecuteQuery(string.Format(sql, workFlowNo));
                if (dt.Rows.Count == 1)
                {
                    HttpContext.Current.Response.Write("1|" + dt.Rows[0]["OperatorInstanceId"].ToString() + "|" + dt.Rows[0]["WorkTaskInstanceId"].ToString() + "|" + dt.Rows[0]["FlowCaptions"].ToString());
                }
                else
                {
                    HttpContext.Current.Response.Write("-1");
                }
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write("e" + e.Message);
            }
        }
        #endregion

        #region 取得待确认考勤记录数
        /// <summary>
        /// 取得待确认考勤记录数
        /// </summary>
        public void GetWorkResult()
        {
            int result = 0;
            try
            {
                int today = DateTime.Now.Day;
                int frmday = int.Parse(HttpContext.Current.Request["frmday"]);
                int endday = int.Parse(HttpContext.Current.Request["endday"]);

                string employeeID = this.User.EmpID.ToString();
                if (today <= endday && today >= frmday) //1-4号提醒
                {
                    result = GetWorkResult(employeeID);
                }
            }
            catch (Exception e)
            {
                //HttpContext.Current.Response.Write("e" + e.Message);
                HttpContext.Current.Response.Write(result.ToString());
            }
            HttpContext.Current.Response.Write(result.ToString());
        }

        /// <summary>
        /// 取得待确认考勤记录数
        /// </summary>
        /// <param name="employeeID"></param>
        public int GetWorkResult(string employeeID)
        {
            string sql = string.Format("select COUNT(*) as totalCount from wkWorkResult where IsValidate='N' and WkStatus not in('正常出勤','非工作日','项目中','加班')  and EmployeeID ='{0}'", employeeID);
            DbSql dbsql = new DbSql();
            return dbsql.ExecuteScalar(sql);
        }
        #endregion

        #region 取得分公司的deptPath
        /// <summary>
        /// 取得分公司的deptPath
        /// </summary>
        /// <returns></returns>
        public string GetChildCompanyDeptPath()
        {
            string deptPath = "";
            string sql = "select DeptID as [key],dept.DeptName as Caption,b.deptname as LCaption,ParentID as  ParentKey,DeptPath as [Path],DeptType from DatDepartment dept,dbo.fn_GetOrganizeAll('333FE8ED-CA2A-497A-A88C-3BB4FB3A1A57') b where (IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]='1900-01-01 00:00:00.000') and dept.DeptID=b.id";
            sql = string.Format(sql, DateTime.Now.ToLongTimeString());
            IList<TreeViewData> list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
            var _DeptID = this.EmpPropertyValues.DeptID;
            var dept = list.Where(p => p.Key.ToString() == _DeptID).First();
            if (dept.LCaption.IndexOf("学校") > 0 || dept.LCaption.IndexOf("分公司") > 0 || dept.LCaption.IndexOf("推广中心") > 0 || dept.LCaption.IndexOf("咨询中心") > 0)
            {
                deptPath = "@001";
                string[] _strDept = dept.LCaption.Replace("->", "_").Split('_');
                string[] _strPath = dept.Path.Replace("->", "_").Split('-');
                for (int i = 0; i < _strDept.Length; i++)
                {
                    if (_strDept[i].IndexOf("分公司") >= 0 || _strDept[i].IndexOf("推广中心") >= 0 || _strDept[i].IndexOf("学校") >= 0 || _strDept[i].IndexOf("咨询中心") >= 0)
                    {
                        deptPath += "-" + _strPath[i];
                        break;
                    }
                    if (i > 0)
                    {
                        deptPath += "-" + _strPath[i];
                    }
                }
            }
            return deptPath;
        }

        /// <summary>
        /// 取得分公司的人员信息
        /// </summary>
        /// <returns></returns>
        public  IList<hrEmployee> GetChildCompanyEmpInfo()
        {
            string deptPath = GetChildCompanyDeptPath();
            if (deptPath == "")
            {
                deptPath = "1<>1";
            }
            string sql = @"select * from hrEmployee where DepartmentID in (select DeptID from DatDepartment where DeptPath like '"+deptPath+"%')";
            IList<hrEmployee> lsthrEmployee = new EnttityBLL().GetEntitysBySqlComm<hrEmployee>(sql);
            return lsthrEmployee;
        }
        #endregion

        #region 核心人才库

        #region 自动生成下级分类编码
        /// <summary>
        /// 自动生成下级分类编码
        /// </summary>
        public void GetChildCategoryNextSeq()
        {
            string ParentID = this.GetStringFromQueryString("ParentID", "");
            HttpContext.Current.Response.Write(GetChildCategoryNextSeq(ParentID));
        }

        /// <summary>
        /// 自动生成下级分类编码
        /// </summary>
        /// <param name="parentID"></param>
        /// <returns></returns>
        public string GetChildCategoryNextSeq(string parentID)
        {
            string sql = string.Format("select IsNULL(MAX(SeqNo),'001') from hrCoreEmpDataBase where ParentID='{0}'", parentID);
            string sql1 = string.Format("select SeqNo from hrCoreEmpDataBase where ID='{0}'", parentID);
            DbSql dbsql = new DbSql();
            DataTable dt = dbsql.ExecuteQuery(sql);
            DataTable dt1 = dbsql.ExecuteQuery(sql1);
            int nextSeq = 1;
            string path = "", nextpath = "";
            if (dt.Rows.Count == 1)
            {
                path = dt.Rows[0][0].ToString();
                string[] ss = path.Split('-');
                if (ss.Length > 1)
                {
                    Int32.TryParse(ss[ss.Length - 1], out nextSeq);
                    nextSeq++;

                    for (int i = 0; i < ss.Length - 1; i++)
                    {
                        nextpath += ss[i] + "-";
                    }
                    for (int i = 0; i < 3 - nextSeq.ToString().Length; i++)
                    {
                        nextpath += "0";
                    }
                    nextpath += nextSeq.ToString();
                }
                else
                {
                    nextpath = dt1.Rows[0][0].ToString() + "-" + path;
                }
            }
            return nextpath;
        }
        #endregion

        #region 判断是否可以删除分类
        /// <summary>
        /// 判断是否可以删除分类
        /// </summary>
        public void IsDelCoreEmpClass()
        {
            string id = this.GetStringFromQueryString("id", "");
            try
            {
                //是否有下级分类
                string sql = string.Format("select id from hrCoreEmpDataBase where ParentID='{0}'", id);
                DbSql dbsql = new DbSql();
                DataTable dt = dbsql.ExecuteQuery(sql);
                if (dt.Rows.Count > 0)
                {
                    HttpContext.Current.Response.Write("2");//有下级分类
                }
                else if (dbsql.ExecuteSql(string.Format("Delete from hrCoreEmpDataBase where id='{0}'", id)) > 0)
                {
                    HttpContext.Current.Response.Write("1");//删除成功
                }
                else
                {
                    HttpContext.Current.Response.Write("0");//删除失败
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");//出错
            }
        }
        #endregion

        #region 是否已存在分类名
        /// <summary>
        /// 是否已存在分类名
        /// </summary>
        public void IsExistsCoreEmpClass()
        {
            string className = this.GetStringFromQueryString("CategoryName", "");
            try
            {
                //是否已存在分类名
                string sql = string.Format("select id from hrCoreEmpDataBase where ClassName='{0}'", className);
                DbSql dbsql = new DbSql();
                DataTable dt = dbsql.ExecuteQuery(sql);
                if (dt.Rows.Count > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        #endregion

        #region 保存选择的人才职务
        /// <summary>
        /// 保存选择的人才职务
        /// </summary>
        public void SaveDatDutyInfo()
        {
            string strJson = this.GetStringFromQueryString("json", "");
            string categoryID = this.GetStringFromQueryString("CategoryID", "");

            var list = (List<V_DatDutyInfo>)Globals.JSonToObject<List<V_DatDutyInfo>>(strJson);
            try
            {
                string sql = "select ID from hrCoreEmpDataBase where IsPost='Y' and DutyInfoID='{0}' and ParentID='{1}' ";
                string insertsql = @"INSERT INTO [hrCoreEmpDataBase]([ID],[ParentID],[ClassName],[IsPost],[DutyInfoID],[SeqNo],[Remark],[AddUser],[AddTime],[ModifyUser],[ModifyTime])
                                        values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')";
                DbSql dbsql = new DbSql();
                string seqNo=""; 
                foreach (var item in list)
                {
                    //先查询是否存在
                    if (dbsql.ExecuteQuery(string.Format(sql, item.ID, categoryID)).Rows.Count < 1)
                    {
                        seqNo = GetChildCategoryNextSeq(categoryID);
                        dbsql.ExecuteSql(string.Format(insertsql, Guid.NewGuid().ToString(), categoryID, item.Name, "Y", item.ID, seqNo, "", this.UserId.ToString(), DateTime.Now, this.UserId.ToString(), DateTime.Now));
                    }
                }
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }
        #endregion

        #region 删除人才职务
        /// <summary>
        /// 删除人才职务
        /// </summary>
        public void DelDatDutyInfo()
        {
            try
            {
                string id = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");

                if (id == string.Empty)
                {
                    HttpContext.Current.Response.Write("-1"); //ID为空
                    return;
                }
                id = "'" + id.Replace(",", "','") + "'";
                BaseEntity instance = null;
                ZX.BLL.Extend.BaseBussnies baseBll = null;
                //删除主表
                instance = ZX.Common.Globals.getEntity("hrCoreEmpDataBase") as BaseEntity;
                string condition = string.Format("ID  in ({0})", id);
                baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                baseBll.delete(condition);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");//出错
            }
        }
        #endregion

        #endregion

        #region 部门剩余调休
        public decimal GetRemTiaoxiuTimeByDept()
        {
            decimal remTiaoxiuTimeByDept=0;
            string sql = @"select SUM(TotalOverTime) TotalOverTime,SUM(TiaoxiuTime) TiaoxiuTime,(SUM(TotalOverTime) -SUM(TiaoxiuTime)) as RemTiaoxiuTime
                            from V_wkOvertimeLeaveTotal
                            where 1=1 
                            and ({0})";
            string leadDeptpaths = "";
            DataTable dt = this.User.GetUserPostDept();
            if (dt != null)
            {
                foreach (DataRow row in dt.Rows)
                {
                    leadDeptpaths += " Deptpath like '" + row["DeptPath"].ToString() + "%' or ";
                }
            }

            if (leadDeptpaths.Length > 1)
            {
                leadDeptpaths = leadDeptpaths.Substring(0, leadDeptpaths.Length - 3);
                DbSql dbsql = new DbSql();
                DataTable wkdt = dbsql.ExecuteQuery(string.Format(sql, leadDeptpaths));
                decimal.TryParse(wkdt.Rows[0]["RemTiaoxiuTime"].ToString(), out remTiaoxiuTimeByDept);
            }

            return remTiaoxiuTimeByDept;
        }

        #endregion

    }
}
